import {
  CoreBindings,
  inject,
  /* inject, Application, CoreBindings, */
  lifeCycleObserver, // The decorator
  LifeCycleObserver, // The interface
} from '@loopback/core';
import fs from 'fs';
import path from 'path';
import { container, log } from '../inversify.config.report';
import puppeteer from 'puppeteer';
import { PagePoolImpl } from '../services/page.management.sevice';
import { RestApplication } from '@loopback/rest';
const pagePoolImpl = container.get(PagePoolImpl);
/* eslint-disable no-console */
/**
 * This class will be bound to the application as a `LifeCycleObserver` during
 * `boot`
 */
@lifeCycleObserver('')
export class InitialPagePoolObserver implements LifeCycleObserver {

  constructor(
    @inject(CoreBindings.APPLICATION_INSTANCE) private app: RestApplication,
  ) { }


  /**
   * This method will be invoked when the application initializes. It will be
   * called at most once for a given application instance.
   */
  async init(): Promise<void> {

  }

  getExecutable() {
    if (process.env.npm_config_puppeteer_executable_path) {
      return process.env.npm_config_puppeteer_executable_path;
    }
    if (process.env.PUPPETEER_EXECUTABLE_PATH) {
      return process.env.PUPPETEER_EXECUTABLE_PATH;
    }
  }
  /**
   * This method will be invoked when the application starts.
   */
  async start(): Promise<void> {
    // Add your logic for init
    if (process.env.jenkins_building) {
      log.debug('will not init browser while jenkins building');
      return;
    }
    const executablePath = this.getExecutable();
    await pagePoolImpl.initBrowsers(executablePath, 1).then(() => pagePoolImpl.createPages(2, this.app.restServer.url!));
    log.info(`init browser from ${executablePath}`);
  }

  /**
   * This method will be invoked when the application stops.
   */
  async stop(): Promise<void> {
    await pagePoolImpl.destroy();
    log.debug('headless page pool destoryed');
  }
}
